package com.jash.encryption;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;


/**
 * A simple {@link Fragment} subclass.
 */
public class MD5Fragment extends Fragment implements View.OnClickListener {


    private TextInputLayout src;
    private TextView rlt;

    public MD5Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_md5, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        src = ((TextInputLayout) view.findViewById(R.id.md5_src));
        rlt = ((TextView) view.findViewById(R.id.md5_rlt));
        view.findViewById(R.id.md5_commit).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String src_str = src.getEditText().getText().toString();
        if (TextUtils.isEmpty(src_str)) {
            src.setError("请入原文");
            src.setErrorEnabled(true);
        } else {
            src.setErrorEnabled(false);
            try {
                MessageDigest md5 = MessageDigest.getInstance("md5");
                byte[] digest = md5.digest(src_str.getBytes("UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (byte b : digest) {
                    builder.append(String.format(Locale.getDefault(), "%02X", b));
                }
                rlt.setText(builder.toString());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
